package cc.chinagps.gateway.client.packet.down;

import cc.chinagps.gateway.client.bean.TerminalType;
import cc.chinagps.gateway.client.packet.BasePacket;
import cc.chinagps.gateway.client.packet.base.PacketAdapter;
import cc.chinagps.gateway.util.CommonUtils;
import cc.chinagps.gateway.util.DateTimeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.nio.charset.StandardCharsets;

@EqualsAndHashCode(callSuper = true)
@Data
public class Packet01 extends PacketAdapter {
    String loginTime;
    short serialNo;
    String iccid;
    byte status = 0;
    int longitude;
    int latitude;

    public Packet01(BasePacket basePacket) {
        super(basePacket);
    }

    public void decodeBusinessData(byte[] data) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer(data);
        TerminalType terminalType = TerminalType.find(getBasePacket().getDeviceInfo().getTerminalType());
        byte[] time = new byte[6];
        buf.readBytes(time);
        loginTime = DateTimeUtil.getDateTime(time, 0, 6);
        serialNo = buf.readShort();
        iccid = buf.readCharSequence(20, StandardCharsets.UTF_8).toString();
        switch (terminalType) {
            case ELECTRONIC_LABEL:
                break;
            case OBD:
                status = buf.readByte();
                break;
            default:
                throw new Exception("terminal type error,terminalType:" + terminalType);
        }
        longitude = buf.readInt();
        latitude = buf.readInt();
    }

    @Override
    public void decodeBusinessData() throws Exception {
        byte[] data = basePacket.getMsgBody();
        decodeBusinessData(data);
    }

    @Override
    public byte[] encodeBussinessData() throws Exception {
        ByteBuf buf = Unpooled.buffer(16);
        TerminalType terminalType = TerminalType.find(getBasePacket().getDeviceInfo().getTerminalType());
        buf.writeBytes(DateTimeUtil.str2DateTime(loginTime));
        buf.writeShort(serialNo);
        byte[] iccidBytes = iccid.getBytes(StandardCharsets.UTF_8);
        if (iccidBytes.length != 20) {
            throw new Exception("iccid length not equal 20,current len:" + iccidBytes.length);
        }
        buf.writeBytes(iccidBytes);
        switch (terminalType) {
            case ELECTRONIC_LABEL:
                break;
            case OBD:
                if (longitude <= 0 || latitude <= 0) {
                    status = 1;
                }
                buf.writeByte(status);
                break;
            default:
                throw new Exception("terminal type error,terminalType:" + terminalType);
        }
        buf.writeInt(longitude);
        buf.writeInt(latitude);
        return CommonUtils.getByteArray(buf);
    }
}
